package com.linghang.demo.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.linghang.demo.domain.Manage;
import com.linghang.demo.domain.ManageExample;
import com.linghang.demo.mapper.ManageMapper;
import com.linghang.demo.req.ManageQueryReq;
import com.linghang.demo.req.ManageSaveReq;
import com.linghang.demo.resp.ManageQueryResp;
import com.linghang.demo.resp.PageResp;
import com.linghang.demo.util.CopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ManageService {
    private int id=10;
    @Resource
    private ManageMapper manageMapper;
    private static final Logger LOG = LoggerFactory.getLogger(ManageService.class);

    public List<Manage> list(){
        return manageMapper.selectByExample(null);
    }

    public PageResp<ManageQueryResp> list(ManageQueryReq req) {
        ManageExample manageExample = new ManageExample();
        ManageExample.Criteria criteria = manageExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getId())) {
            criteria.andIdEqualTo(  req.getId() );
        }

        PageHelper.startPage(req.getPage(), req.getSize());
        List<Manage> manageList = manageMapper.selectByExample(manageExample);

        PageInfo<Manage> pageInfo = new PageInfo<>(manageList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        // List<ManageResp> respList = new ArrayList<>();
        // for (Manage manage : manageList) {
        //     // ManageResp manageResp = new ManageResp();
        //     // BeanUtils.copyProperties(manage, manageResp);
        //     // 对象复制
        //     ManageResp manageResp = CopyUtil.copy(manage, ManageResp.class);
        //
        //     respList.add(manageResp);
        // }

        // 列表复制
        List<ManageQueryResp> list = CopyUtil.copyList(manageList, ManageQueryResp.class);

        PageResp<ManageQueryResp> pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);

        return pageResp;
    }

    /**
     * 保存
     */
    public void save(ManageSaveReq req) {
        Manage manage= CopyUtil.copy(req, Manage.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            manage.setId(id++);
            manageMapper.insert(manage);
        } else {
            // 更新
            manageMapper.updateByPrimaryKey(manage);
        }
    }

    
    public void  delete(int id){
        manageMapper.deleteByPrimaryKey(id);
    }
}
